package models

import (
	"github.com/astaxie/beego/orm"
	//"fmt"
	//"strconv"
	"fmt"
	"strconv"
)

type NumberGroupMap struct {
	Id         int64
	Group_id   int64
	Number_id  int64
	Map_id     int64
	Has_called int
	//NumberGroup *NumberGroup
	//Numbers *AiNumbers
	Group_name     string
	Dst_number     string
	Num_state      int
	Last_call_time string
	Num_own        string
	Param1         string
	Param2         string
	Param3         string
	Param4         string
	Param5         string
	Param6         string
	Param7         string
	Param8         string
	Param9         string
	Param10        string
}

type GroupMap struct {
	Id           int64
	Group_id     int64
	Number_id    int64
	Has_called   int
	Param1       string
	Param2       string
	Param3       string
	Param4       string
	Param5       string
	Param6       string
	Param7       string
	Param8       string
	Param9       string
	Param10      string
	Param1_type  string
	Param2_type  string
	Param3_type  string
	Param4_type  string
	Param5_type  string
	Param6_type  string
	Param7_type  string
	Param8_type  string
	Param9_type  string
	Param10_type string
}

func (a *GroupMap) TableName() string {
	return TableName("number_group_map")
}

func GroupMapAdd(a *GroupMap) (int64, error) {
	return orm.NewOrm().Insert(a)
}
func NumberGroupMapGetByName(groupId string) (*NumberGroupMap, error) {
	a := new(NumberGroupMap)
	err := orm.NewOrm().QueryTable(TableName("number_group_map")).Filter("group_id", groupId).One(a)
	if err != nil {
		return nil, err
	}
	return a, nil
}
func NumberGroupMapGetListCount(gid int) (error, int64) {
	var total int64
	SqlStr := "select  count(1) " +
		"from ai_number_group as g,ai_numbers as n,ai_number_group_map as m " +
		"where g.id = " + strconv.Itoa(gid) + " and m.group_id=g.id and m.number_id = n.id "

	err := orm.NewOrm().Raw(SqlStr).QueryRow(&total)

	return err, total
}
func NumberGroupMapGetList(page, pageSize, gid int) ([]NumberGroupMap, int64) {
	offset := (page - 1) * pageSize
	list := make([]NumberGroupMap, 0)
	//query := orm.NewOrm().QueryTable(TableName("number_group_map"))
	SqlStr := "select g.id group_id,n.id number_id,m.id map_id, g.group_name group_name,n.dst_number dst_number, " +
		"m.has_called num_state,n.last_call_time last_call_time,n.num_own num_own,m.param1,m.param2,m.param3,m.param4,m.param5,m.param6,m.param7,m.param8,m.param9,m.param10 " +
		"from ai_number_group as g,ai_numbers as n,ai_number_group_map as m " +
		"where g.id = " + strconv.Itoa(gid) + " and m.group_id=g.id and m.number_id = n.id " +
		"limit " + strconv.Itoa(pageSize) + " offset " + strconv.Itoa(offset)
	orm.NewOrm().Raw(SqlStr).QueryRows(&list)
	//fmt.Println("---------->",list)
	//if len(filters) >2 {
	//	l := len(filters)
	//	for k := 0; k < l; k += 2 {
	//		query = query.Filter(filters[k].(string), filters[k+1])
	//	}
	//}
	err, total := NumberGroupMapGetListCount(gid)
	if err != nil {
		fmt.Println("get count error :", err)
	}
	//query.Limit(pageSize, offset).All(&list)

	return list, total
}

func NumberGroupMapGetById(id int) (*NumberGroupMap, error) {
	r := new(NumberGroupMap)
	err := orm.NewOrm().QueryTable(TableName("number_group_map")).Filter("id", id).One(r)
	if err != nil {
		return nil, err
	}
	return r, nil
}
func (a *GroupMap) Delete() error {
	if _, err := orm.NewOrm().Delete(a); err != nil {
		return err
	}
	return nil
}

func AiNumbersMapGetById(id int) (*GroupMap, error) {
	r := new(GroupMap)
	err := orm.NewOrm().QueryTable(TableName("number_group_map")).Filter("id", id).One(r)
	if err != nil {
		return nil, err
	}
	return r, nil
}

//获取今日任务数量
func GetNumberCounts(userId int) (int, error) {
	var authStr = " "
	if userId != 1 {
		authStr = " and t.tk_owner=" + strconv.Itoa(userId)
	}
	sqlStr := "select count(g) " +
		"from ai_task t ,ai_number_group_map g " +
		"where TO_CHAR(tk_start_time,'yyyy-MM-dd') > TO_CHAR((current_timestamp - interval '1 day'),'yyyy-MM-dd') " +
		"and t.tk_num_group=g.group_id " + authStr + ";"

	var numberCount int
	err := orm.NewOrm().Raw(sqlStr).QueryRow(&numberCount)
	if err != nil {
		ErrorLog(err)
		return 0, err
	}

	return numberCount, nil
}

type DurationModel struct {
	Adc      int64
	Duration int64
}

//获取今日完成任务数量
func GetDoneNumberCounts(userId int) (int, DurationModel, error) {
	var authStr = " "
	if userId != 1 {
		authStr = " and account_id=" + strconv.Itoa(userId)
	}
	sqlStr := "select count(1) " +
		"from ai_cdr " +
		"where TO_CHAR(start_time,'yyyy-MM-dd') > TO_CHAR((current_timestamp - interval '1 day'),'yyyy-MM-dd') " + authStr + ";"

	var numberCount int
	err := orm.NewOrm().Raw(sqlStr).QueryRow(&numberCount)
	if err != nil {
		ErrorLog(err)
		return 0, DurationModel{}, err
	}
	adcstr := "select sum(duration)/count(1) adc,sum(duration) duration from ai_cdr where TO_CHAR(start_time,'yyyy-MM-dd') > TO_CHAR((current_timestamp - interval '1 day'),'yyyy-MM-dd') " + authStr + " ;"
	var durationModel = DurationModel{}
	err = orm.NewOrm().Raw(adcstr).QueryRow(&durationModel)
	if err != nil {
		ErrorLog(err)
		return 0, DurationModel{}, err
	}
	return numberCount, durationModel, nil
}

//获取接通了的数量
func GetConnectCounts(userId int) (int, error) {
	var authStr = " "
	if userId != 1 {
		authStr = " and account_id=" + strconv.Itoa(userId)
	}
	sqlStr := "select count(1) " +
		"from ai_cdr " +
		"where TO_CHAR(start_time,'yyyy-MM-dd') > TO_CHAR((current_timestamp - interval '1 day'),'yyyy-MM-dd') " +
		"and duration!=0 " + authStr + ";"

	var numberCount int
	err := orm.NewOrm().Raw(sqlStr).QueryRow(&numberCount)
	if err != nil {
		ErrorLog(err)
		return 0, err
	}

	return numberCount, nil
}

//获取未接通的数量
func GetUnconnectCounts(userId int) (int, error) {
	var authStr = " "
	if userId != 1 {
		authStr = " and account_id=" + strconv.Itoa(userId)
	}
	sqlStr := "select count(1) " +
		"from ai_cdr " +
		"where TO_CHAR(start_time,'yyyy-MM-dd') > TO_CHAR((current_timestamp - interval '1 day'),'yyyy-MM-dd') " +
		"and duration=0 " + authStr + ";"

	var numberCount int
	err := orm.NewOrm().Raw(sqlStr).QueryRow(&numberCount)
	if err != nil {
		ErrorLog(err)
		return 0, err
	}

	return numberCount, nil
}

func CheckNumberMap(groupid, numid int64) bool {
	sqlStr := "SELECT count(*) FROM ai_number_group_map WHERE group_id=" + strconv.FormatInt(groupid, 10) + " and number_id=" + strconv.FormatInt(numid, 10)
	var count int
	err := orm.NewOrm().Raw(sqlStr).QueryRow(&count)
	if err != nil || count > 0 {
		return false
	}
	return true

}

//如果有新值添加成功，就修改task的状态，变为进行中
func UptateTaskState(groupid int64) error {
	sqlStr := "UPDATE ai_task SET tk_state=0 FROM ai_number_group_map WHERE ai_number_group_map.group_id=" + strconv.FormatInt(groupid, 10) + " AND ai_task.tk_num_group=" + strconv.FormatInt(groupid, 10)
	_, err := orm.NewOrm().Raw(sqlStr).Exec()
	if err != nil {
		return err
	}
	return nil

}

//如果有新值添加成功，就修改task的状态，变为进行中
func UptateResetNumberMap(groupid int64) error {
	sqlStr := "UPDATE ai_number_group_map SET has_called=0 WHERE group_id=" + strconv.FormatInt(groupid, 10)
	_, err := orm.NewOrm().Raw(sqlStr).Exec()
	if err != nil {
		return err
	}
	return nil

}
